import request from '@/utils/request'

// 菜单相关API
export const menuApi = {
  // 获取菜单列表
  getMenuList() {
    return request({
      url: '/api/menus',
      method: 'get'
    })
  },

  // 获取用户菜单权限
  getUserMenus() {
    return request({
      url: '/api/user/menus',
      method: 'get'
    })
  },

  // 创建菜单
  createMenu(data) {
    return request({
      url: '/api/menus',
      method: 'post',
      data
    })
  },

  // 更新菜单
  updateMenu(id, data) {
    return request({
      url: `/api/menus/${id}`,
      method: 'put',
      data
    })
  },

  // 删除菜单
  deleteMenu(id) {
    return request({
      url: `/api/menus/${id}`,
      method: 'delete'
    })
  },

  // 批量更新菜单排序
  updateMenuOrder(data) {
    return request({
      url: '/api/menus/order',
      method: 'put',
      data
    })
  },

  // 获取菜单树结构
  getMenuTree() {
    return request({
      url: '/api/menus/tree',
      method: 'get'
    })
  },

  // 检查菜单权限
  checkMenuPermission(menuKey) {
    return request({
      url: `/api/menus/${menuKey}/permission`,
      method: 'get'
    })
  }
}

// 权限相关API
export const permissionApi = {
  // 获取权限列表
  getPermissionList() {
    return request({
      url: '/api/permissions',
      method: 'get'
    })
  },

  // 获取角色权限
  getRolePermissions(roleId) {
    return request({
      url: `/api/roles/${roleId}/permissions`,
      method: 'get'
    })
  },

  // 更新角色权限
  updateRolePermissions(roleId, permissions) {
    return request({
      url: `/api/roles/${roleId}/permissions`,
      method: 'put',
      data: { permissions }
    })
  },

  // 检查用户权限
  checkUserPermission(permission) {
    return request({
      url: `/api/permissions/check`,
      method: 'post',
      data: { permission }
    })
  }
}

// 角色相关API
export const roleApi = {
  // 获取角色列表
  getRoleList() {
    return request({
      url: '/api/roles',
      method: 'get'
    })
  },

  // 创建角色
  createRole(data) {
    return request({
      url: '/api/roles',
      method: 'post',
      data
    })
  },

  // 更新角色
  updateRole(id, data) {
    return request({
      url: `/api/roles/${id}`,
      method: 'put',
      data
    })
  },

  // 删除角色
  deleteRole(id) {
    return request({
      url: `/api/roles/${id}`,
      method: 'delete'
    })
  }
}

// 菜单缓存相关
export const menuCache = {
  // 缓存菜单数据
  cacheMenuData(data) {
    localStorage.setItem('menuData', JSON.stringify(data))
  },

  // 获取缓存的菜单数据
  getCachedMenuData() {
    const data = localStorage.getItem('menuData')
    return data ? JSON.parse(data) : null
  },

  // 清除菜单缓存
  clearMenuCache() {
    localStorage.removeItem('menuData')
  },

  // 缓存菜单权限
  cacheMenuPermissions(permissions) {
    localStorage.setItem('menuPermissions', JSON.stringify(permissions))
  },

  // 获取缓存的菜单权限
  getCachedMenuPermissions() {
    const data = localStorage.getItem('menuPermissions')
    return data ? JSON.parse(data) : null
  },

  // 清除菜单权限缓存
  clearMenuPermissionsCache() {
    localStorage.removeItem('menuPermissions')
  }
}

// 菜单工具函数
export const menuUtils = {
  // 构建菜单树
  buildMenuTree(menus, parentId = null) {
    const tree = []
    for (const menu of menus) {
      if (menu.parentId === parentId) {
        const children = this.buildMenuTree(menus, menu.id)
        if (children.length > 0) {
          menu.children = children
        }
        tree.push(menu)
      }
    }
    return tree.sort((a, b) => a.order - b.order)
  },

  // 扁平化菜单树
  flattenMenuTree(menus) {
    const result = []
    const flatten = (items) => {
      for (const item of items) {
        result.push(item)
        if (item.children && item.children.length > 0) {
          flatten(item.children)
        }
      }
    }
    flatten(menus)
    return result
  },

  // 根据路径查找菜单
  findMenuByPath(menus, path) {
    const find = (items) => {
      for (const item of items) {
        if (item.path === path) {
          return item
        }
        if (item.children && item.children.length > 0) {
          const found = find(item.children)
          if (found) return found
        }
      }
      return null
    }
    return find(menus)
  },

  // 获取面包屑路径
  getBreadcrumbs(menus, currentPath) {
    const breadcrumbs = []
    const findPath = (items, path, result = []) => {
      for (const item of items) {
        if (item.path === path) {
          return [...result, item]
        }
        if (item.children && item.children.length > 0) {
          const found = findPath(item.children, path, [...result, item])
          if (found) return found
        }
      }
      return null
    }
    return findPath(menus, currentPath) || []
  },

  // 过滤菜单权限
  filterMenusByPermission(menus, userType, permissions) {
    return menus.filter(menu => {
      // 检查角色权限
      if (menu.roles && !menu.roles.includes(userType)) {
        return false
      }
      
      // 检查具体权限
      if (menu.permission && !permissions.includes(menu.permission)) {
        return false
      }
      
      // 检查多个权限（任一满足即可）
      if (menu.permissions && !menu.permissions.some(p => permissions.includes(p))) {
        return false
      }
      
      // 如果有子菜单，递归过滤
      if (menu.children && menu.children.length > 0) {
        menu.children = this.filterMenusByPermission(menu.children, userType, permissions)
        // 如果子菜单全部被过滤掉，且父菜单没有path，则隐藏父菜单
        if (menu.children.length === 0 && !menu.path) {
          return false
        }
      }
      
      return true
    })
  }
}

export default {
  menuApi,
  permissionApi,
  roleApi,
  menuCache,
  menuUtils
} 